package com.cl.code.database.mbp.log;

import org.apache.ibatis.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author chengliang
 * @since 1.0.0
 */
public class CustomDataLog implements Log {
    Logger log;
    private static final String PREFIX_SQL = "==>  Preparing:";
    private static final String PREFIX_PARAMS = "==> Parameters:";
    private static final String PREFIX_TOTAL = "<==      Total:";
    private static final String PREFIX_UPDATE = "<==    Updates:";

    private static final ThreadLocal<LogContext> CONTEXT = ThreadLocal.withInitial(LogContext::new);

    public CustomDataLog(String clazz) {
        log = LoggerFactory.getLogger(clazz);
    }

    @Override
    public boolean isDebugEnabled() {
        return log.isInfoEnabled();
    }

    @Override
    public boolean isTraceEnabled() {
        return log.isTraceEnabled();
    }

    @Override
    public void error(String s, Throwable e) {
        log.error(s, e);
    }

    @Override
    public void error(String s) {
        log.error(s);
    }

    @Override
    public void debug(String s) {
        LogContext logContext = CONTEXT.get();
        if (s.startsWith(PREFIX_SQL)) {
            logContext.sql = s.substring(PREFIX_SQL.length()).trim();
        } else if (s.startsWith(PREFIX_PARAMS)) {
            logContext.params = s.substring(PREFIX_PARAMS.length()).trim();
        } else if (s.startsWith(PREFIX_TOTAL)) {
            logContext.total = s.substring(PREFIX_TOTAL.length()).trim();
            // 全部信息准备好，合并打印
            logContext.log();
            CONTEXT.remove();
        } else if (s.startsWith(PREFIX_UPDATE)) {
            logContext.updateCount = s.substring(PREFIX_UPDATE.length()).trim();
            // 全部信息准备好，合并打印
            logContext.log();
            CONTEXT.remove();
        } else {
            log.debug(s);
        }
    }

    @Override
    public void trace(String s) {
        log.trace(s);
    }

    @Override
    public void warn(String s) {
        log.warn(s);
    }

    private static class LogContext {
        private final Logger log = LoggerFactory.getLogger("DATA_LOG");
        private String sql;
        private String params;
        private String total;
        private String updateCount;

        public void log() {
            String count = null;
            String type = null;
            if (sql.contains("SELECT")) {
                type = "query";
                count = total;
            } else if (sql.contains("UPDATE") || sql.contains("INSERT") || sql.contains("DELETE")) {
                type = "update";
                count = updateCount;
            }
            log.info("{} SQL: {} | Params: {} | Count: {}", type, this.sql, this.params, count);
        }

    }


}
